package com.example.rocketmqp.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @eo.api-type http
 * @eo.groupName 默认分组
 * @eo.path /Producer
 */

@Slf4j
@RestController
@RequestMapping("/Producer")
public class ProducerController {
    @Resource
    private DefaultMQProducer producer;

    @Value("${rocketmq.topic}")
    private String topic;
    @Value("${rocketmq.tag}")
    private String tag;
    @GetMapping("/send")
    private void sendMsg(@RequestParam("message")String message) {
        MessageQueue messageQueue=new MessageQueue();
        messageQueue.setQueueId(0);
        messageQueue.setTopic(topic);
        messageQueue.setBrokerName("broker-a");
        Message msg;
        try {
            log.error(topic + ":" + tag + ":" + message);
            msg = new Message(topic, tag, UUID.randomUUID().toString(), message.getBytes(StandardCharsets.UTF_8));
//          private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
            msg.setDelayTimeLevel(2);
            SendResult result = producer.send(msg);
            if (result.getSendStatus().equals(SendStatus.SEND_OK)||result.getSendStatus().equals(SendStatus.SLAVE_NOT_AVAILABLE)) {
                System.out.println("消息发送成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
